package commands

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
)

// NewSystemCommand 创建系统管理命令
func NewSystemCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "system",
		Short: "系统管理",
		Long:  "获取系统信息、能力、版本和健康状态",
	}

	cmd.AddCommand(newSystemInfoCommand())
	cmd.AddCommand(newSystemCapabilitiesCommand())
	cmd.AddCommand(newSystemVersionCommand())
	cmd.AddCommand(newSystemHealthCommand())

	return cmd
}

func newSystemInfoCommand() *cobra.Command {
	var (
		outputFormat string
		connectionID string
	)

	cmd := &cobra.Command{
		Use:   "info",
		Short: "获取系统信息",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			info, err := client.System().GetSystemInfo(context.Background(), connectionID)
			if err != nil {
				return fmt.Errorf("获取系统信息失败: %w", err)
			}

			return printOutput(info, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newSystemCapabilitiesCommand() *cobra.Command {
	var (
		outputFormat string
		connectionID string
	)

	cmd := &cobra.Command{
		Use:   "capabilities",
		Short: "获取系统能力",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			capabilities, err := client.System().GetCapabilities(context.Background(), connectionID)
			if err != nil {
				return fmt.Errorf("获取系统能力失败: %w", err)
			}

			return printOutput(capabilities, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	cmd.Flags().StringVarP(&connectionID, "connection", "c", "", "连接 ID")
	return cmd
}

func newSystemVersionCommand() *cobra.Command {
	var outputFormat string

	cmd := &cobra.Command{
		Use:   "version",
		Short: "获取 API 版本",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			version, err := client.System().GetVersion(context.Background())
			if err != nil {
				return fmt.Errorf("获取 API 版本失败: %w", err)
			}

			return printOutput(version, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	return cmd
}

func newSystemHealthCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "health",
		Short: "健康检查",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.System().HealthCheck(context.Background())
			if err != nil {
				return fmt.Errorf("健康检查失败: %w", err)
			}

			fmt.Println("✅ 系统健康")
			return nil
		},
	}

	return cmd
}
